package com.xu.cloud.common.aop;

import com.xu.cloud.common.lock.DistributeLock;
import com.xu.cloud.common.lock.IDistributeLock;
import com.xu.cloud.common.util.ExceptionUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

/**
 * 分布式锁切面
 *
 * @author xuguan
 * @since 2025/3/21
 */
@Aspect
public class DistributeLockAspect {
    private final IDistributeLock distributeLock;

    public DistributeLockAspect(IDistributeLock distributeLock) {
        this.distributeLock = distributeLock;
    }

    @Around("@annotation(lockAnnotation)")
    public Object around(ProceedingJoinPoint pjp, DistributeLock lockAnnotation) {
        Object ret;

        try {
            distributeLock.lock(lockAnnotation.lockName());
            ret = pjp.proceed();
        } catch (Throwable e) {
            throw ExceptionUtil.wrapXuCloudException(e);
        } finally {
            distributeLock.unlock();
        }

        return ret;
    }
}